package com.zhiyume.util;


import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.zhiyume.service.util.DateUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;


/**
 * 阿里云 OSS文件类
 *
 * @author lizb
 */

public class OSSClientUtil {
    Log log = LogFactory.getLog(OSSClientUtil.class);
    // endpoint以杭州为例，其它region请按实际情况填写
    private String endpoint;
    // accessKey
    private String accessKeyId;
    private String accessKeySecret;
    //空间
    private String bucketName;
    //文件存储目录
    private String filedir = "data/";
    private OSSClient ossClient;

    private String key;

    public OSSClientUtil() {
        this.endpoint = OSSClientConstants.ENDPOINT;
        this.accessKeyId = OSSClientConstants.ACCESS_KEY_ID;
        this.accessKeySecret = OSSClientConstants.ACCESS_KEY_SECRET;
        this.bucketName = OSSClientConstants.BUCKET_NAME;
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        this.filedir = filedir;
    }

    public OSSClientUtil(String filedir) {
        this.endpoint = OSSClientConstants.ENDPOINT;
        this.accessKeyId = OSSClientConstants.ACCESS_KEY_ID;
        this.accessKeySecret = OSSClientConstants.ACCESS_KEY_SECRET;
        this.bucketName = OSSClientConstants.BUCKET_NAME;
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        this.filedir = filedir;
    }

    /**
     * 初始化
     */
    public void init() {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 销毁
     */
    public void destory() {
        ossClient.shutdown();
    }

    /**
     * 上传图片
     *
     * @param url
     */
    public void uploadImg2Oss(String url) throws Exception {
        File fileOnServer = new File(url);
        FileInputStream fin;
        try {
            fin = new FileInputStream(fileOnServer);
            String[] split = url.split("/");
            this.uploadFile2OSS(fin, split[split.length - 1]);
        } catch (FileNotFoundException e) {
            throw new Exception("图片上传失败");
        }

    }

    public String uploadImg2Oss(MultipartFile file) throws Exception {
        if (file.getSize() > 1024 * 1024) {
            throw new Exception("上传图片大小不能超过1M！");
        }
        String originalFilename = file.getOriginalFilename();
//        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
//        Random random = new Random();
//        String name = random.nextInt(10000) + System.currentTimeMillis() + substring;

        try {
            InputStream inputStream = file.getInputStream();
            this.uploadFile2OSS(inputStream, originalFilename);
            return originalFilename;
        } catch (Exception e) {
            throw new Exception("图片上传失败");
        }

    }

    public String uploadImg2Oss(MultipartFile file,File tempFile) throws Exception {
        if (file.getSize() > 1024 * 1024) {
            throw new Exception("上传图片大小不能超过1M！");
        }
        String originalFilename = file.getOriginalFilename();
//        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
//        Random random = new Random();
//        String name = random.nextInt(10000) + System.currentTimeMillis() + substring;

        try {
            InputStream inputStream = FileUtils.openInputStream(tempFile);
            this.uploadFile2OSS(inputStream, originalFilename);
            return originalFilename;
        } catch (Exception e) {
            throw new Exception("图片上传失败");
        }

    }

    /**
     * 删除图片
     */
    public void deleteFile(String filedir, String key){
        if("".equals(filedir) || filedir == null) filedir = this.filedir;
        ossClient.deleteObject(bucketName, key);
        System.out.println("*******删除" + bucketName + "下的文件" + key + "成功");
    }

    public void deleteFile(String key){
        ossClient.deleteObject(bucketName, key);
        System.out.println("-------删除" + bucketName + "下的文件" + key + "成功");
    }



    /**

     * 获得图片路径

     *

     * @param fileUrl

     * @return

     */

    public String getImgUrl(String fileUrl) {
        if (!StringUtils.isEmpty(fileUrl)) {
            String[] split = fileUrl.split("/");
            return this.getUrl(this.filedir + split[split.length - 1]);
        }
        return null;
    }



    /**

     * 上传到OSS服务器  如果同名文件会覆盖服务器上的

     *

     * @param instream 文件流

     * @param fileName 文件名称 包括后缀名

     * @return 出错返回"" ,唯一MD5数字签名

     */

    public String uploadFile2OSS(InputStream instream, String fileName) {

        String ret = "";

        try {

            //创建上传Object的Metadata

            ObjectMetadata objectMetadata = new ObjectMetadata();

            objectMetadata.setContentLength(instream.available());

            objectMetadata.setCacheControl("no-cache");

            objectMetadata.setHeader("Pragma", "no-cache");

            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));

            objectMetadata.setContentDisposition("inline;filename=" + fileName);

            //上传文件
            fileName = DateUtil.date2String(new Date(), DateUtil.DATE_PATTERN.YYYYMMDDHHMMSS) + "_" + fileName;
            key = filedir + fileName;
            PutObjectResult putResult = ossClient.putObject(bucketName, key, instream, objectMetadata);

            ret = putResult.getETag();
            System.out.println("==============上传至阿里云OSS返回MD5串为=========="+ret);
        } catch (IOException e) {

            log.error(e.getMessage(), e);

        } finally {

            try {

                if (instream != null) {

                    instream.close();

                }

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

        return ret;

    }



    /**

     * Description: 判断OSS服务文件上传时文件的contentType

     *

     * @param FilenameExtension 文件后缀

     * @return String

     */

    public static String getcontentType(String FilenameExtension) {

        if (FilenameExtension.equalsIgnoreCase("bmp")) {

            return "image/bmp";

        }

        if (FilenameExtension.equalsIgnoreCase("gif")) {

            return "image/gif";

        }

        if (FilenameExtension.equalsIgnoreCase("jpeg") ||

                FilenameExtension.equalsIgnoreCase("jpg") ||

                FilenameExtension.equalsIgnoreCase("png")) {

            return "image/jpeg";

        }

        if (FilenameExtension.equalsIgnoreCase("html")) {

            return "text/html";

        }

        if (FilenameExtension.equalsIgnoreCase("txt")) {

            return "text/plain";

        }

        if (FilenameExtension.equalsIgnoreCase("vsd")) {

            return "application/vnd.visio";

        }

        if (FilenameExtension.equalsIgnoreCase("pptx") ||

                FilenameExtension.equalsIgnoreCase("ppt")) {

            return "application/vnd.ms-powerpoint";

        }

        if (FilenameExtension.equalsIgnoreCase("docx") ||

                FilenameExtension.equalsIgnoreCase("doc")) {

            return "application/msword";

        }

        if (FilenameExtension.equalsIgnoreCase("xml")) {

            return "text/xml";

        }

        return "image/jpeg";

    }



    /**

     * 获得url链接

     *

     * @param key

     * @return

     */

    public String getUrl(String key) {
        if("".equals(key) || key == null) key = this.key;
        // 设置URL过期时间为10年  3600l* 1000*24*365*10

        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);

        // 生成URL

        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);

        if (url != null) {

            return url.toString();

        }

        return null;

    }

    /**
     * 获取图片被阿里云裁剪过的图片地址
     * @param style 处理图片的样式
     * @param imgName 图片名称
     * @return
     */
    public String getImgSytleUrl(String style,String imgName) {
        // 设置过期时间为10年
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(this.bucketName, imgName, HttpMethod.GET);
        req.setExpiration(expiration);
        req.setProcess(style);
        URL signedUrl = ossClient.generatePresignedUrl(req);
        return String.valueOf(signedUrl);
    }
}
